package org.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.JdbcUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.List;
import java.util.Properties;

/**
 * @author young
 * @create 2021-01-11-11:03
 * @description
 */
public class BaseDao {
    private Connection connection;

    private PreparedStatement preparedStatement;

    private ResultSet resultSet;

    private static String driver;

    private static String url;

    private static String username;

    private static String password;

    //静态代码块
    static {
        initial();
    }

    //读取数据库配置文件
    public static void initial() {
        Properties properties = new Properties();
        InputStream inputStream = BaseDao.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("driverClassName");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");

    }


    //创建连接的方法
    public Connection getConnection() {
        try {
            // alter +enter
            Class.forName(driver);
            return DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    //关闭连接
    public void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    // 增删改
    public int executeUpdate(String sql, Object[] params) {
        int count = 0;
        if (getConnection()!=null) {
            try {
                preparedStatement = getConnection().prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, params[i]);
                }
                count = preparedStatement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return count;
    }


    //查询
    public ResultSet executeSQL(String sql, Object[] params) {
        if (this.getConnection()!=null) {
            try {
                Connection connection = getConnection();
                preparedStatement = connection.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, params[i]);
                }
                resultSet = preparedStatement.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resultSet;
    }

    /*===========================================================================================*/
    private static DruidDataSource dataSource = null;

    static {
//        读取jdbc.prooerties配置文件，将其加载为流进行加载
        InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        try {
            pros.load(is);
//            创建数据库连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(pros);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取与数据库的连接
     *
     * @return Connection 对象
     */
    public static Connection getConnection1() {
        try {
//            通过上面创建的数据库连接池调用druid包中的getConnection方法获取与数据库的连接
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 关闭数据库连接，放回数据库连接池
     *
     * @param conn
     */
    public static void close(Connection conn) {
        DbUtils.closeQuietly(conn);

    }

    private QueryRunner queryRunner = new QueryRunner();

    /**
     * 实现数据库的insert、delete和update操作
     *
     * @return -1表示修改失败
     * >0表示修改了数据库中的数据的行数
     */
    public int update(Connection conn, String sql, Object... args) {
        try {
            int update = queryRunner.update(conn, sql, args);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 查询返回一个javabean语句
     *
     * @param conn  数据库连接对象
     * @param sql   查询的sql语句
     * @param clazz 返回的对象类型
     * @param args  sql对应的参数值
     * @param <T>   返回类型的泛型
     * @return
     */
    public <T> T queryForOne(Connection conn, String sql, Class<T> clazz, Object... args) {
        try {
            BeanHandler<T> beanHandler = new BeanHandler<>(clazz);
            T query = queryRunner.query(conn, sql, beanHandler, args);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询返回多个javabean的sql语句
     *
     * @param conn  数据库连接对象
     * @param sql   查询的sql语句
     * @param clazz 返回的对象类型
     * @param args  sql对应的参数值
     * @param <T>   返回类型的泛型
     * @return
     */
    public <T> List<T> queryForList(Connection conn, String sql, Class<T> clazz, Object... args) {
        try {
            BeanListHandler<T> beanListHandler = new BeanListHandler<>(clazz);
            List<T> query = queryRunner.query(conn, sql, beanListHandler, args);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询返回特殊值
     *
     * @param conn 数据库连接对象
     * @param sql  查询的sql语句
     * @param args sql对应的参数值
     * @return
     */
    public Object queryForSingleValue(Connection conn, String sql, Object... args) {
        try {
            ScalarHandler scalarHandler = new ScalarHandler();
            return queryRunner.query(conn, sql, scalarHandler, args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


}
